<template>
  <div>
    <el-card class="search-card">
      <BasicForm
        ref="formData"
        formItemWidth="120px"
        isScalingBtn
        :defaultExpandStatus="false"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        :handleClearForm="handleClearForm"
        @getFormData="getFormData"
      >
        <RemoteSelect
          ref="remoteSelect"
          slot="selectSupplier"
          placeholder="请选择供应商"
          :optionKeys="['supplierName', 'supplierCode']"
          :echoValue="formData.supplierCode"
          :echoOptions="[formData.supplierName, formData.supplierCode]"
          :remoteSelectOptions="remoteOptionsBySupplier"
          :handleClickButton="handleChooseSupplier"
          @getSelect="getSupplierInfo"
        />
      </BasicForm>
    </el-card>
    <el-card class="table-card">
      <skus-table
        showPagination
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :total="pagination.total"
        :pageSizes="pageSizes"
        :pagination="pagination"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <div slot="content_context">
          <!-- 按钮操作栏 -->
          <BtnRender :render="renderBtnsBar" />
        </div>
      </skus-table>
    </el-card>
    <!-- 表格表列字段设置弹框 -->
    <TableColumnSettingDialog
      :visible.sync="tableColumnSetting.visible"
      :rowKey="tableColumnSetting.rowKey"
      :queryApi="tableColumnSetting.queryApi"
      :submitUrl="tableColumnSetting.submitUrl"
      @getTableColumns="getTableColumns"
    />
    <SelectSupplierDialog
      :visible.sync="dialogVisible.supplier"
      @getSupplierInfo="getSupplierInfo"
    />
  </div>
</template>
<script>
import { getBtnsId } from '@/libs/btnsPermission';
import { requestToData, requestToExport } from '@/api/commonHttp';
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import TableColumnSettingDialog from '@/pages/commodity/components/TableColumnSettingDialog';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';
import SelectSupplierDialog from '@/pages/commodity/components/SelectSupplierDialog';
import { getBtnsBar } from '@/utils/getBtnsRender';
import { formItemList } from './constants';
import { getSearchParamBySearchType, getConfigColumns } from '@/utils/getUtils';
import { createExcelByExport } from '@/utils/bizUtils';
import { querySupplierService } from '@/api/commodity/common';

export default {
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
    TableColumnSettingDialog,
    RemoteSelect,
    SelectSupplierDialog
  },
  data () {
    return {
      tableColumnSetting: { // 表格表列字段设置
        visible: false, // 弹框显隐
        rowKey: 'querySettingDictionaryId',
        queryApi: { url: '/sysback/querySetting/getListByType?type=1' },
        submitUrl: '/sysback/querySetting/saveOrUpdate'
      },
      formItemList: formItemList,
      formData: {
        categoryUuid: '', // 分类id
        categoryName: '', // 分类名称
        productName: '', // 商品名称
        brandName: '', // 品牌名称
        spuNo: '', // SPU编码
        skuNo: '', // SKU编码
        supplierCode: '', // 供应商编码
        supplierName: '', // 供应商名称
        saleAreaName: '', // 销售区域
        saleAreaUuid: '', // 销售区域
        saleProvinceName: '', // 销售省
      },
      tableInfo: {
        list: [],
        columns: [],
        loading: false,
      },
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      pageSizes: [10, 20, 30, 40],
      btnLoading: {
        export: false
      },
      dialogVisible: {
        supplier: false
      }
    }
  },
  mounted () {
    const { categoryUuid, saleAreaUuid, supplierCode } = this.$route.query;
    if (categoryUuid) {
      this.formData.supplierCode = supplierCode;
      this.formData.categoryUuid = categoryUuid;
      this.formData.saleAreaUuid = saleAreaUuid;
    }
    this.loadInitDataInMounted();
  },
  methods: {
    renderBtnsBar (h) {
      const btnsBar = [
        {
          label: '导出',
          method: this.handleExport,
          icon: 'el-icon-download',
          hasAuth: true,
          loading: this.btnLoading.export,
          type: 'primary',
          size: 'mini'
        },
        {
          label: '字段显示设置',
          method: this.handleShowFieldsSetting,
          icon: 'el-icon-setting',
          type: 'primary',
          size: 'mini'
        },
      ]
      return getBtnsBar(h, btnsBar, this.showBtn, 'start');
    },
    // 表单内容为空
    isEmptyByForm () {
      return Object.values(this.formData).every(item => !item);
    },
    // 表单查询
    handleQueryForm () {
      this.pagination.pageNum = 1;
      this.getTableDataBySearchForm();
    },
    // 导出
    handleExport () {
      if (this.isEmptyByForm()) {
        return this.$message.warning('请至少输入一个筛选项');
      }
      this.exportTableData();
    },
    // 字段显示设置
    handleShowFieldsSetting () {
      this.tableColumnSetting.visible = true;
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.pageNum = val;
      this.getTableDataBySearchForm();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageSize = val;
      this.getTableDataBySearchForm();
    },
    // 加载初始数据在mounted时期
    loadInitDataInMounted () {
      this.getInitTableColumns();
    },
    // 获取表格columns
    getTableColumns (columns) {
      this.tableInfo.columns.length = 0;
      this.$nextTick(() => {
        this.tableInfo.columns = getConfigColumns(columns);
      });
    },
    // 获取表单数据
    getFormData (data) {
      this.formData = data;
    },
    // 获取查询数据入参
    getParamsBySearchForm () {
      const fixedParams = [
        { name: 'categoryUuid', value: this.formData.categoryUuid },
        { name: 'categoryUuid_q', value: 'IN' },
        { name: 'saleAreaUuid', value: this.formData.saleAreaUuid },
        { name: 'saleAreaUuid_q', value: 'EQ' },
      ]
      const { pageNum, pageSize } = this.pagination;
      const searchParam = getSearchParamBySearchType(formItemList, this.formData).concat(fixedParams);
      return {
        nowPage: pageNum,
        pageShow: pageSize,
        searchParam: JSON.stringify(searchParam)
      }
    },
    // 获取初始表格columns
    async getInitTableColumns () {
      const { url } = this.tableColumnSetting.queryApi;
      const retData = await requestToData({
        url,
        type: 'get'
      }, () => { this.tableInfo.loading = true; }, () => { this.tableInfo.loading = false; });
      if (retData) {
        this.tableInfo.columns = getConfigColumns(retData).map((i) => {
          if (i.key === 'supplierName') {
            i.formatter = (row) => {
              return <router-link target="_blank" to={{ name: 'viewQualifiedSupplier', query: { id: row.supplierId } }}>{ row.supplierName }</router-link>
            }
          }
          if (i.key === 'spuNo') {
            i.formatter = (row) => {
              const { productUuid, spuNo } = row;
              return <router-link target="_blank" to={{ name: 'SPUManageDetail', query: { productUuid, spuNo } }}>{ row.spuNo }</router-link>
            }
          }
          return i
        })
      }
      if (this.formData.categoryUuid) {
        this.getTableDataBySearchForm()
      }
    },
    // 初始化表格数据
    initTableData (list) {
      if (!list) { return []; }
      return list.map(item => ({ ...item, ...item.authDepartmentVo }));
    },
    // 获取表格数据
    async getTableDataBySearchForm () {
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      const retData = await requestToData({
        url: '/sysback/supplyarea/getSupplySaleAreaProudctListInner',
        type: 'post',
        data: this.getParamsBySearchForm()
      }, () => { this.tableInfo.loading = true; }, () => { this.tableInfo.loading = false; });
      if (retData) {
        this.tableInfo.list = this.initTableData(retData.results);
        this.pagination.total = retData.totalNum;
      }
    },
    // 导出表格数据
    async exportTableData () {
      const searchParam = getSearchParamBySearchType(formItemList, this.formData);
      const res = await requestToExport({
        url: '/sysback/supplyarea/exportSupplyInfoData',
        type: 'post',
        data: { searchParam: JSON.stringify(searchParam) }
      }, () => { this.btnLoading.export = true; }, () => { this.btnLoading.export = false; });
      createExcelByExport({ res, excelTitle: '供货信息表' });
    },
    // 供应商相关
    // 表单特殊清空
    handleClearForm () {
      this.clearSupplierInfo();
    },
    // 选择供应商
    handleChooseSupplier () {
      this.dialogVisible.supplier = true;
    },
    // 远程搜索供应商
    async remoteOptionsBySupplier (queryString, loadingFn) {
      const data = {
        nowPage: 1,
        pageShow: 20,
        searchParam: JSON.stringify([
          { name: 'supplierName', value: queryString },
          { name: 'supplierName_q', value: 'Like' }
        ]),
      };
      const res = await querySupplierService(data, loadingFn);
      if (res?.retData) {
        return res.retData.results.map(item => ({ supplierCode: item.supplierNo, ...item }))
      }
      return [];
    },
    // 获取弹框选择的供应商信息
    getSupplierInfo (data) {
      this.formData.supplierName = data.supplierName;
      this.formData.supplierCode = data.supplierNo;
    },
    // 清空供应商信息
    clearSupplierInfo () {
      this.$refs.remoteSelect.clearValue()
    }
  }
}
</script>
